import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';



@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  phone: any = ''; //手机号
  confirm: number;//验证码
  password: any;//密码
  sendText: string = '点击获取验证码';
  timer: any = null;
  i: number = 60;
  canSend: boolean = false;
  inputTimeout: any = null;
  delay: number = 1000;
  loading: any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public loadingCtrl: LoadingController,
    public ToastCtrl: ToastController,
    public Http: HttpClient,
  ) {
  }
  //加载框
  showLoading() {
    this.loading = this.loadingCtrl.create({
      spinner: 'bubbles',
      dismissOnPageChange: true,
      content: '加载中',
      duration: 80000
    });
    this.loading.present();
  }
  //封装公共弹窗
  showToast(message) {
    let toast = this.ToastCtrl.create({
      message: message,
      duration: 1000,
      position: 'top'
    });
    toast.present();
  }
  //验证手机号
  confirmPhone(e) {
    if (this.delay > 0) {
      if (this.inputTimeout) {
        window.clearTimeout(this.inputTimeout);
      }
      this.inputTimeout = setTimeout(() => {
        if (!(/^1[34578]\d{9}$/.test(this.phone))) {
          this.showToast('手机号格式不对');
        } else {
          this.canSend = true;
        }
      }, this.delay)
    } else {
    }
  }
  //发送短信
  sendMsg() {
    if (this.canSend) {
      this.canSend = false;
      this.timer = setInterval(() => {
        this.i--;
        this.sendText = `重发验证码${this.i}s`;
        if (this.i == 0) {
          this.i = 60;
          this.sendText = '重新发送';
          this.canSend = true;
          clearInterval(this.timer);
          return;
        }
      }, 1000)
      this.Http.get('https://easy-mock.com/mock/5b2385e3debe3c5977248a16/wscn/captcha').subscribe((res: any) => {
        if (res.code == 200) {
          this.confirm = res.data.captcha;
          this.showToast(`发送成功,验证码为${res.data.captcha}`);
        }
      })
    }
  }

  //登陆
  login() {
    this.showLoading();
    let params = {
      phone: this.phone,
      captcha: this.confirm
    }
    this.Http.post('https://easy-mock.com/mock/5b2385e3debe3c5977248a16/wscn/submit', params).subscribe((res: any) => {
      this.showToast(res.data.messgae);
      this.loading.dismiss();
    })
  }
}
